<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2018/1/9
 * Time: 上午9:57
 */


header("Content-type: text/html; charset=utf-8");

require  '../vendor/autoload.php';

$text_finder = new SimilarText\Finder('为提供文件备份', ['百度网盘为您提供文件的网络备份、同步和分享服务。', '前度网盘为您提供文件的删除操作、撤销个分析服务', '115网盘网络备份、同步和分享服务,为你提供文件']);

//拆分字符串
function mbStringToArray($string, $encoding = 'UTF-8') {
    $arrayResult = array();

    while ($iLen = mb_strlen($string, $encoding)) {
        array_push($arrayResult, mb_substr($string, 0, 1, $encoding));
        $string = mb_substr($string, 1, $iLen, $encoding);
    }
    return $arrayResult;
}

//str1是输入,str2是数据库里面的数据
function LCS_cn($str1, $str2, $encoding = 'UTF-8') {
    $mb_len1 = mb_strlen($str1, $encoding);
    $mb_len2 = mb_strlen($str2, $encoding);
    $mb_str1 = mbStringToArray($str1, $encoding);
    $mb_str2 = mbStringToArray($str2, $encoding);
    $len = $mb_len1 > $mb_len2 ? $mb_len1 : $mb_len2;
    $dp = array();
    for ($i = 0; $i <= $len; $i++) {
        $dp[$i] = array();
        $dp[$i][0] = 0;
        $dp[0][$i] = 0;
    }
    $max = 0;
    $new_text = "";
    for ($i = 1; $i <= $mb_len1+1; $i++) {
        for ($j = 1; $j <= $mb_len2+1; $j++) {
            if ($mb_str1[$i - 1] == $mb_str2[$j - 1]) {
                $dp[$i][$j] = $dp[$i - 1][$j - 1] + 1;
                if ($dp[$i][$j] > $max) {
                    $max = $dp[$i][$j];
                }
            } else {
                $dp[$i][$j] = 0;
            }
//            echo $dp[$i][$j]." ";
        }
//        echo '<br>';
    }
    $ranges = [];
    $last_m = 0;
    for ($k = 0;$k <$mb_len1;$k++) {
        for ($m = $last_m;$m < $mb_len2;$m++) {
            $row = $k;
            $col = $m;
            while ($dp[$row][$col] >0 && (($row<$mb_len1 && $col < $mb_len2) && $dp[$row+1][$col+1]>0)){
                $dp[$row][$col] = 0;
                $row++;
                $col++;
            }
            if ($dp[$row][$col]>2){
                $ranges[] = ['start' => $col - $dp[$row][$col], 'length' => $dp[$row][$col]];
                $dp[$row][$col] = 0;
            }
        }
    }
    for ($i = 1; $i <= $mb_len1+1; $i++) {
        for ($j = 1; $j <= $mb_len2+1; $j++) {
            echo $dp[$i][$j]." ";
        }
        echo '<br>';
    }
    usort($ranges,"sortRange");
    $start = 0;
    foreach ($ranges as $value) {
        $new_text .= mb_substr($str2,$start,$value['start']-$start);
        $text = mb_substr($str2,$value['start'],$value['length']);
        $new_text .= '<font style="color:red">'.$text.'</font>';
        $start = $value['start'] + $value['length'];
    }
    $new_text .= mb_substr($str2, $start);
    print_r($ranges);
    return $new_text;
}

function sortRange($one,$two){
    return $one['start'] > $two['start'] ? 1:-1;
}
echo LCS_cn('下列简单函数及其定义域是经常用到的','注本题是求函数的自然定义域一般方法是先写出构成所求函数的各个简单函数的定义域，再求出这些定义域的交集，即得所求定义域。下列简单函数及其定义域是经常用到的');

